package com.yz.jdd.base.activity;

import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.widget.Toast;

import com.trello.rxlifecycle.components.support.RxFragment;

import rx.subscriptions.CompositeSubscription;
public class BaseFragment extends RxFragment implements IBaseView {
    protected Toast myToast;
    float scale;
    LoadingDialog loadingDialog;
    ToastDialog toastDialog;
    Handler toastHandler;
    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    public static <T extends BaseFragment> T newInstance(Class<T> clazz, Bundle args) {
        T fragment = null;
        try {
            fragment = clazz.newInstance();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (fragment != null) {
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scale = getResources().getDisplayMetrics().density;
    }

    /**
     * 显示服务器提示msg
     */
    @Override
    public void showToast(String msg) {

        if (myToast == null) {
            myToast = Toast.makeText(getContext(), msg,
                    Toast.LENGTH_SHORT);
        } else {
            myToast.setText(msg);
            myToast.setDuration(Toast.LENGTH_SHORT);
        }
        myToast.show();

    }

    /**
     * 显示服务器提示msg
     */
    @Override
    public void showToastDialog(String msg) {
        if (toastDialog != null){
            toastDialog.dismiss();
        }

        if (toastHandler != null){
            toastHandler.removeCallbacksAndMessages(null);
        }
        toastDialog = new ToastDialog(getContext(), msg);
        toastDialog.show();
        toastHandler = new Handler();
        toastHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (toastDialog != null){
                    toastDialog.dismiss();
                }
            }
        }, 3000);


    }

    /**
     * 显示loading
     */
    @Override
    public void showLoading(String msg) {

        loadingDialog = new LoadingDialog(getContext(), msg);
        loadingDialog.show();

    }

    /**
     * 隐藏loading()
     */
    @Override
    public void dismissLoading() {
        if (loadingDialog != null){
            loadingDialog.dismiss();
        }
    }


    @Override
    public void showLoadingNoCancelable(String msg) {
        this.showLoading(msg);
        loadingDialog.setCancelable(false);
    }

    /**
     * 根据密度dip计算px
     */
    public int getPx(int dip) {

        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    @Override
    public CompositeSubscription getCompositeSubscription() {
        return compositeSubscription;
    }
}
